#!/usr/bin/env python
# -*- coding: utf-8 -*-
from string import Template
from tack.lib import json_app, content_headers, status_codes
from datetime import datetime
from tack_ocie.api.util import state_def, build_row_dict, build_row_dict_for_sql, build_columns_values_sql


get_one = """
SELECT * FROM ocie_schedule
WHERE (state_finish IS NULL 
    AND schedule_id = $schedule_id
    AND state_key <> $canceled_state) 
OR (state_finish IS NULL 
    AND parent_id = $schedule_id 
    AND state_key <> $canceled_state)
"""


set_state_finish = """
UPDATE ocie_schedule
SET state_finish = '$time_stamp'
WHERE schedule_id = $old_state_id
"""


insert_state = "INSERT INTO ocie_schedule"


def cancel(environ, start_response):
    schedule_id = environ['dispatcher.groups']['schedule_id']
    canceled_state = state_def.CANCELED
    sql = Template(get_one).substitute(locals())
    cursor = environ['connection'].cursor()
    cursor.execute(sql)
    rows = cursor.fetchall()
    if rows:
        old_state_id = rows[0].schedule_id
        throwaway = datetime.now()
        time_stamp = throwaway.strftime('%Y-%m-%d %H:%M:%S')
        state_dict = build_row_dict_for_sql(cursor.description, rows[0])
        if not state_dict['parent_id']:
            state_dict['parent_id'] = state_dict['schedule_id']
        del state_dict['schedule_id']
        state_dict['state_start'] = "'" + time_stamp + "'"
        del state_dict['state_finish']
        state_dict['state_key'] = str(state_def.CANCELED)
        sql = insert_state + build_columns_values_sql(state_dict)
        cursor.execute(sql)
        environ['connection'].commit()
        sql = Template(set_state_finish).substitute(locals())
        cursor.execute(sql)
        environ['connection'].commit()
        output = 'Canceled'
    else:
        start_response(status_codes.not_found, content_headers.default_plain())
        return ['404 Not Found']
    return json_app(output)(environ, start_response)


